package com.chen.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.Result;

import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.Impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/users")
@SuppressWarnings("all")
@Api(value = "UserController", tags = "用户接口")
public class UserController {
    private static Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource //自动装配
    private HttpServletRequest request;


    @Resource
    private UserServiceImpl userService;

    @RequestMapping(value = "/info/{t}", method = RequestMethod.GET)
    @ResponseBody
    public Result getInfo(@PathVariable String t) { //绑定它传过来的值到方法的参数上
        log.info("UserController-info: timestamp = " + t);
        String token = "";
        Long originalKeepAlive = null;
        Long timestamp = null;//时间戳
        try {
            timestamp = Long.parseLong(t);//是将参数转换成long的包装类
            token = request.getHeader("token");
            originalKeepAlive = Long.valueOf(request.getHeader("keepAlive"));
        } catch (Exception e) {
            log.error("[info] get info is error {}", e.getMessage());
        }
        log.info("UserController-info: token = " + token);
        log.info("UserController-info: originalKeepAlive = " + originalKeepAlive);
        return userService.info(token, timestamp, originalKeepAlive);
        //return userService.info(token);


    }

    @ResponseBody
    @RequestMapping(value = "/logout{t}", method = RequestMethod.POST)
    @ApiOperation("用户退出")
    public Result getLogOut(@PathVariable String t) {
        String token = "";
        Long originalKeepAlive = null;
        try {
            token = request.getHeader("token");
            originalKeepAlive = Long.valueOf(request.getHeader("keepAlive"));
        } catch (Exception e) {
            log.error("The Request Headers or params is null.");
        }
        log.info("UserController-info: token = " + token);
        log.info("UserController-info: originalKeepAlive = " + originalKeepAlive);
        return userService.logout(token, originalKeepAlive);

    }

    //依赖注入
    @Resource
    UserMapper userMapper;

    //注册
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error(50000, "用户名重复");
        }
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }

        userMapper.insert(user);
        return Result.success();
    }

    //登录
    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public Result<?> login(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (res == null) {
            return Result.error(50001, "用户名或密码错误");
        }
        //登录成功后 初始化用户信息模板
        UserInfo userInfo = new UserInfo(res);
//        String token = ObjectId.next();
//        Map<String, Object> map = new HashMap<>();
//        long time = System.currentTimeMillis() + 1000L;
//        map.put("token", token);

//        UserInfo info=new UserInfo(res);

        return Result.success(userInfo);


    }

    //    新增
    @PostMapping
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();

    }

    //更新
    @PutMapping
    public Result<?> update(@RequestBody User user) {
        userMapper.updateById(user);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(userMapper.selectById(id));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

    //    查询
    @GetMapping("/query")
    public Result<?> findPage1(@RequestParam(defaultValue = "1") Integer pageNum,  //页号
                               @RequestParam(defaultValue = "10") Integer pageSize, //一页展示的数量
                               @RequestParam(defaultValue = "") String search) {

//        模糊查询
        LambdaQueryWrapper<User> warapper = Wrappers.<User>lambdaQuery().like(User::getNick, search);
        if (StrUtil.isBlank(search)) {
            warapper.like(User::getNick, search);
        }
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), warapper);
        return Result.success(userPage);

    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().like(User::getNick, search);
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getNick, search);
        }
        Page<User> userPage = userMapper.findPage(new Page<>(pageNum, pageSize), search);
        return Result.success(userPage);
    }


}
